package com.ruoyi.develop.factory.factoryMaterialMain.service.impl;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

import javax.annotation.Resource;

import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.factory.factoryProduceWork.domain.FactoryProduceWork;
import com.ruoyi.develop.factory.factoryProduceWork.mapper.FactoryProduceWorkMapper;
import com.ruoyi.develop.factory.factoryTestSample.domain.FactoryTestSample;
import com.ruoyi.develop.factory.factoryTestSample.mapper.FactoryTestSampleMapper;
import com.ruoyi.develop.factory.factoryTestStandard.domain.FactoryTestStandard;
import com.ruoyi.develop.factory.factoryTestStandard.mapper.FactoryTestStandardMapper;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.mapper.GoodsOrderInMapper;
import com.ruoyi.develop.lvDaohuoDetail.domain.LvDaohuoDetail;
import com.ruoyi.develop.lvDaohuoDetail.mapper.LvDaohuoDetailMapper;
import com.ruoyi.develop.lvYifahuomingxi.domain.LvYifahuomingxi;
import com.ruoyi.develop.project.domain.Project;
import com.ruoyi.develop.project.mapper.ProjectMapper;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.mapper.ProjectBaseInfoMapper;
import com.ruoyi.export.service.IExportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.factory.factoryMaterialMain.mapper.FactoryMaterialMainMapper;
import com.ruoyi.develop.factory.factoryMaterialMain.domain.FactoryMaterialMain;
import com.ruoyi.develop.factory.factoryMaterialMain.service.IFactoryMaterialMainService;

/**
 * 原材料（主材）Service业务层处理
 *
 * @author lmm
 * @date 2024-11-06
 */
@Service
public class FactoryMaterialMainServiceImpl implements IFactoryMaterialMainService {
    @Resource
    private FactoryMaterialMainMapper factoryMaterialMainMapper;
    @Resource
    private FactoryProduceWorkMapper factoryProduceWorkMapper;
    @Resource
    private GoodsOrderInMapper goodsOrderInMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private ProjectBaseInfoMapper projectBaseInfoMapper;
    @Resource
    private LvDaohuoDetailMapper lvDaohuoDetailMapper;
    @Resource
    private FactoryTestStandardMapper factoryTestStandardMapper;
    @Resource
    private FactoryTestSampleMapper factoryTestSampleMapper;
    @Autowired
    private IExportService exportService;



    /**
     * 查询原材料（主材）
     *
     * @param id 原材料（主材）主键
     * @return 原材料（主材）
     */
    @Override
    public FactoryMaterialMain selectById(String id) {
        return factoryMaterialMainMapper.selectById(id);
    }

    /**
     * 查询原材料（主材）列表
     *
     * @param entity 原材料（主材）
     * @return 原材料（主材）
     */
    @Override
    public List<FactoryMaterialMain> selectList(FactoryMaterialMain entity) {
        return factoryMaterialMainMapper.selectList(entity);
    }

    /**
     * 新增原材料（主材）
     *
     * @param entity 原材料（主材）
     * @return 结果
     */
    @Override
    public int insert(FactoryMaterialMain entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }

        if(StringUtils.isNotBlank(entity.getWorkOrderId())) {
            FactoryProduceWork workOrder =  factoryProduceWorkMapper.selectById(entity.getWorkOrderId());
            if (StringUtils.isNotBlank(workOrder.getProNo())) {
                Project project = projectMapper.selectProjectByCode(workOrder.getProNo());
                entity.setProjectId(project.getId());
                entity.setProjectCode(project.getCode());
            }
            if (StringUtils.isNotBlank(workOrder.getMaterialsCode())) {
                entity.setGoodsId(workOrder.getMaterialsCode());
                GoodsOrderIn goods = goodsOrderInMapper.selectByCode(workOrder.getMaterialsCode());
                entity.setGoodsId(goods.getId());
                entity.setGoodsName(goods.getName());
                entity.setGoodsModel(goods.getModel());
            }
        }

        if(StringUtils.isNotBlank(entity.getDaohuoDetailId())) {
            LvDaohuoDetail lvDaohuoDetail = lvDaohuoDetailMapper.selectById(entity.getDaohuoDetailId());
            if(lvDaohuoDetail!=null && StringUtils.isNotBlank(lvDaohuoDetail.getProjectId())){
                ProjectBaseInfo order = projectBaseInfoMapper.selectById(lvDaohuoDetail.getProjectId());
                entity.setProjectId(order.getProject().getId());
                entity.setProjectCode(order.getProject().getCode());
            }
            GoodsOrderIn goods = goodsOrderInMapper.selectById(lvDaohuoDetail.getGoodId());
            entity.setGoodsId(goods.getId());
            entity.setGoodsName(goods.getName());
            entity.setGoodsModel(goods.getModel());
            entity.setName(goods.getName());
            entity.setProducer(lvDaohuoDetail.getSupplierName());
            entity.setGoodsSaleId(lvDaohuoDetail.getGoodsSaleId());
        }

        if(StringUtils.isNotBlank(entity.getSampleId())) {
            FactoryTestSample sample = factoryTestSampleMapper.selectById(entity.getSampleId());
            if(StringUtils.isNotBlank(sample.getGoodsId())) {
                GoodsOrderIn goods = goodsOrderInMapper.selectById(sample.getGoodsId());
                entity.setGoodsId(goods.getId());
                entity.setGoodsName(goods.getName());
                entity.setGoodsModel(goods.getModel());
                entity.setName(goods.getName());
            }
        }
        if(StringUtils.isBlank(entity.getInspectNumber())){
            String todayDate = DateUtils.dateTime();
            String inspectNumberMax = factoryMaterialMainMapper.getMaxInspectNumberByDate(todayDate);
            // 如果存在 则加1 否则返回0001
            if (inspectNumberMax != null) {
                inspectNumberMax =  Long.parseLong(inspectNumberMax) + 1+"";
            }
            else {
                inspectNumberMax = todayDate+"0001";
            }
            entity.setInspectNumber(inspectNumberMax);
        }

        if(StringUtils.isBlank(entity.getBatchNumber())){
            String todayDate = DateUtils.dateTime();
            String batchNumberMax = factoryMaterialMainMapper.getMaxBatchNumberByDate(todayDate);
            // 如果存在 则加1 否则返回0001
            if (batchNumberMax != null) {
                batchNumberMax =  Long.parseLong(batchNumberMax) + 1+"";
            }
            else {
                batchNumberMax = todayDate+"0001";
            }
            entity.setBatchNumber(batchNumberMax);
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        generateInspectReport(entity);
        return factoryMaterialMainMapper.insert(entity);
    }

    /**
     * 修改原材料（主材）
     *
     * @param entity 原材料（主材）
     * @return 结果
     */
    @Override
    public int update(FactoryMaterialMain entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        if(StringUtils.isBlank(entity.getInspectNumber())){
            String todayDate = DateUtils.dateTime();
            String inspectNumberMax = factoryMaterialMainMapper.getMaxInspectNumberByDate(todayDate);
            // 如果存在 则加1 否则返回0001
            if (inspectNumberMax != null) {
                inspectNumberMax =  Long.parseLong(inspectNumberMax) + 1+"";
            }
            else {
                inspectNumberMax = todayDate+"0001";
            }
            entity.setInspectNumber(inspectNumberMax);
        }

        if(StringUtils.isBlank(entity.getBatchNumber())){
            String todayDate = DateUtils.dateTime();
            String batchNumberMax = factoryMaterialMainMapper.getMaxBatchNumberByDate(todayDate);
            // 如果存在 则加1 否则返回0001
            if (batchNumberMax != null) {
                batchNumberMax =  Long.parseLong(batchNumberMax) + 1+"";
            }
            else {
                batchNumberMax = todayDate+"0001";
            }
            entity.setBatchNumber(batchNumberMax);
        }
        generateInspectReport(entity);
        factoryMaterialMainMapper.update(entity);
        checkPass(entity);
        return 1;
    }

    @Override
    public int update(FactoryMaterialMain entity, String user) {
        entity.setUpdateBy(user);
        entity.setUpdateTime(DateUtils.getNowDate());
        checkPass(entity);
        generateInspectReport(entity);
        return factoryMaterialMainMapper.update(entity);
    }


    /**
     * 批量删除原材料（主材）
     *
     * @param ids 需要删除的原材料（主材）主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return factoryMaterialMainMapper.deleteByIds(ids);
    }

    /**
     * 删除原材料（主材）信息
     *
     * @param id 原材料（主材）主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return factoryMaterialMainMapper.deleteById(id);
    }

    @Override
    public FactoryMaterialMain selectByInspectNumber(String inspectNumber) {
        return factoryMaterialMainMapper.selectByInspectNumber(inspectNumber);
    }


    @Override
    public boolean checkPass(FactoryMaterialMain factoryMaterialMain){

        FactoryMaterialMain materialMain =  factoryMaterialMainMapper.selectByInspectNumber(factoryMaterialMain.getInspectNumber());
        if(materialMain ==null){
            materialMain = factoryMaterialMainMapper.selectById(factoryMaterialMain.getId());
        }

        GoodsOrderIn goodsOrderIn = goodsOrderInMapper.selectById(materialMain.getGoodsId());
        String materialId = goodsOrderIn.getMaterialMain();

        FactoryTestStandard param = new FactoryTestStandard();
        param.setMaterialId(materialId);
        param.setTestType("factory_material_main");
        List<FactoryTestStandard> standardList =  factoryTestStandardMapper.selectList(param);

        PropertyDescriptor[] pds = new PropertyDescriptor[0];
        try {
            pds = Introspector.getBeanInfo(FactoryMaterialMain.class).getPropertyDescriptors();
        } catch (IntrospectionException e) {
            throw new RuntimeException(e);
        }
        List<String> propNames = new ArrayList<>();
        for (PropertyDescriptor pd : pds) {
            if(!Arrays.toString(BusinessConstants.standardIgnoreType).contains(pd.getName())){
                propNames.add(pd.getName());
            }
        }

        StringBuilder description = new StringBuilder();

        for (FactoryTestStandard standard : standardList) {
            for(String propName : propNames){
                if (standard.getPropName().equals(propName)){
                    Field propField = null;
                    try {
                        propField = factoryMaterialMain.getClass().getDeclaredField(propName);
                        String propNameCh = standard.getPropNameCh();
                        // 设置访问权限为true，以便可以访问私有字段
                        propField.setAccessible(true);
                        // 获取name字段的值
                        System.out.println(propField.get(factoryMaterialMain));
                        if(propField.get(factoryMaterialMain) == null){
                            continue;
                        }
                        System.out.println(":::::::::::::::::::"+propField.get(factoryMaterialMain));
                        // 判断是否为数字
                        String value = propField.get(factoryMaterialMain)+"";
                        // 判断是否为数字
                        if(!StringUtils.isNumeric(value)){
                            continue;
                        }
                        BigDecimal currentValue =  new BigDecimal(value);
                        String min = standard.getPropValueMin();
                        String max = standard.getPropValueMax();

                        // 转换为BigDecimal类型
                        BigDecimal minValue = new BigDecimal(min);
                        BigDecimal maxValue = new BigDecimal(max);

                        // 判断合格标准
                        if(BusinessConstants.STANDARD_COMPARE_TYPE_RANGE_CC.equals(standard.getResultType())){
                            // 比较大小
                            if (currentValue.compareTo(minValue) < 0 || currentValue.compareTo(maxValue) > 0) {
                                description.append(propNameCh).append(" 的值 ").append(currentValue).append(" 超出了标准范围 [").append(min).append(", ").append(max).append("]");
                            }
                        }

                        if(BusinessConstants.STANDARD_COMPARE_TYPE_RANGE_CO.equals(standard.getResultType())){
                            if (currentValue.compareTo(minValue) < 0 || currentValue.compareTo(maxValue) >= 0) {
                                description.append(propNameCh).append(" 的值 ").append(currentValue).append(" 超出了标准范围 [").append(min).append(", ").append(max).append(")");
                            }
                        }

                        if(BusinessConstants.STANDARD_COMPARE_TYPE_RANGE_OC.equals(standard.getResultType())){
                            if (currentValue.compareTo(minValue) <= 0 || currentValue.compareTo(maxValue) > 0) {
                                description.append(propNameCh).append(" 的值 ").append(currentValue).append(" 超出了标准范围 (").append(min).append(", ").append(max).append("]");
                            }
                        }

                        if(BusinessConstants.STANDARD_COMPARE_TYPE_RANGE_OO.equals(standard.getResultType())){
                            if (currentValue.compareTo(minValue) <= 0 || currentValue.compareTo(maxValue) >= 0) {
                                description.append(propNameCh).append(" 的值 ").append(currentValue).append(" 超出了标准范围 (").append(min).append(", ").append(max).append(")");
                            }
                        }
                        if(BusinessConstants.STANDARD_COMPARE_TYPE_GT.equals(standard.getResultType())){
                            if (currentValue.compareTo(minValue) < 0) {
                                description.append(propNameCh).append(" 的值 ").append(currentValue).append(" 超出了标准范围 (").append(min).append(", ").append("∞)");
                            }
                        }
                        if(BusinessConstants.STANDARD_COMPARE_TYPE_EGT.equals(standard.getResultType())){
                            if (currentValue.compareTo(minValue) <= 0) {
                                description.append(propNameCh).append(" 的值 ").append(currentValue).append(" 超出了标准范围 [").append(min).append(", ").append("∞)");
                            }
                        }
                        if(BusinessConstants.STANDARD_COMPARE_TYPE_LT.equals(standard.getResultType())){
                            if (currentValue.compareTo(maxValue) > 0) {
                                description.append(propNameCh).append(" 的值 ").append(currentValue).append(" 超出了标准范围 (-∞").append(", ").append(max).append(")");
                            }
                        }
                        if(BusinessConstants.STANDARD_COMPARE_TYPE_ELT.equals(standard.getResultType())){
                            if (currentValue.compareTo(maxValue) >= 0) {
                                description.append(propNameCh).append(" 的值 ").append(currentValue).append(" 超出了标准范围 (-∞").append(", ").append(max).append("]");
                            }
                        }


                    } catch (NoSuchFieldException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        if(StringUtils.isBlank(description.toString())){
            description.append("检测合格");
            factoryMaterialMain.setResult(description.toString());
            return true;
        }
        if(StringUtils.isNotBlank(description.toString())){
            factoryMaterialMain.setResult(description.toString());
            return false;
        }
        return true;
    }



    /** 根据质检数据生成质检报告 */
    public void generateInspectReport(FactoryMaterialMain factoryMaterialMain){
        Map<String, Object> params = new HashMap<>();
        params.put("entity", factoryMaterialMain);
        params.put("inspectDate", DateUtils.formatDate(factoryMaterialMain.getArriveInspectDate(),"yyyy年MM月dd日"));
        String fileName = "原材料检验报告.docx";
        String templateName = "原材料检验报告.docx";
        String url = exportService.convertDocxAndUpload(fileName, params, templateName);
        factoryMaterialMain.setMaterialReport(url);
    }


    public void updateRukumingxiByDaohuo(String daohuoDetailId, String rukuMingxiId) {
        factoryMaterialMainMapper.updateRukumingxiByDaohuo(daohuoDetailId,rukuMingxiId);
    }







}
